interface PropsType {
  canvas: HTMLCanvasElement;
  frameRate?: number;
}

class Recorder {
  canvas: HTMLCanvasElement;
  frameRate: number;
  mediaRecorder: MediaRecorder | null = null;
  chunks: Blob[];
  constructor(props: PropsType) {
    this.canvas = props.canvas;
    this.frameRate = props.frameRate || 15;
    this.mediaRecorder = null;
    this.chunks = [];
  }

  /**
   * 开始录制
   */
  start() {
    console.log('Recording started');
    const stream = this.canvas.captureStream(this.frameRate);
    this.mediaRecorder = new MediaRecorder(stream, {
      mimeType: 'video/webm; codecs=vp9'
    });
    this.mediaRecorder.ondataavailable = (event) => {
      if (event.data.size > 0) {
        this.chunks.push(event.data);
      }
    };
    this.mediaRecorder.start();
  }

  /**
   * 停止录制
   * @returns Promise<Blob | null>
   */
  stop(): Promise<Blob | null> {
    console.log('Recording stopped');
    return new Promise((resolve) => {
      if (this.mediaRecorder) {
        this.mediaRecorder.onstop = () => {
          const blob = new Blob(this.chunks, { type: 'video/webm' });
          resolve(blob);
        };
        this.mediaRecorder.stop();
      } else {
        resolve(null);
      }
    });
  }
}

export default Recorder;
